package com.kksoft.android.xiaoliaobaike.fetcher;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalHttp;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import android.os.Handler;
import android.os.Message;

import com.kksoft.android.xiaoliaobaike.Const;
import com.kksoft.android.xiaoliaobaike.model.Series;

public class SeriesFetcher {
	Handler seriesHandler;

	public SeriesFetcher(Handler seriesHandler) {
		this.seriesHandler = seriesHandler;
	}

	public static final String PAGE_URL = "http://xiaoliaobaike.com/groups/13/children?page=";
	public static final String BASE_URL = "http://xiaoliaobaike.com";

	public void fetch(int page) {
		new Thread(new FetchThread(page)).start();
	}

	private class FetchThread implements Runnable {

		private int page;

		public FetchThread(int page) {
			this.page = page;
		}

		public void run() {
			String url = PAGE_URL + page;

			// 获取数据
			Message toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_FETCH_START);
			seriesHandler.sendMessage(toSend);

			String pageContent = null;
			try {
				pageContent = FinalHttp.get(url);
				if (pageContent == null || pageContent == "" || pageContent.length() == 0) {
					toSend = seriesHandler.obtainMessage(Const.MSG_URL_NOT_FOUND);
					seriesHandler.sendMessage(toSend);
					return;
				}
			} catch (Exception e) {
				toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_FETCH_ERROR);
				toSend.obj = e.getMessage();
				seriesHandler.sendMessage(toSend);
				return;
			}

			toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_FETCH_FINISH);
			seriesHandler.sendMessage(toSend);

			// 解析数据
			toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_ANALYSIS_START);
			seriesHandler.sendMessage(toSend);

			List<Series> seriesList = null;

			try {
				seriesList = parsePage(pageContent);
			} catch (Exception e) {
				toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_ANALYSIS_ERROR);
				toSend.obj = e.getMessage();
				seriesHandler.sendMessage(toSend);
				return;
			}
			toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_ANALYSIS_FINISH);
			seriesHandler.sendMessage(toSend);

			toSend = seriesHandler.obtainMessage(Const.MSG_SERIES_LIST);
			toSend.obj = seriesList;
			seriesHandler.sendMessage(toSend);
		}

		private List<Series> parsePage(String html) {
			List<Series> seriesList = new ArrayList<Series>(12);

			try {
				// Document parse = Jsoup.parse(html);
				Document parse = Parser.parse(html, BASE_URL);

				// 获取最后一页
				// pagebar
				int lastPage = 0;

				try {
					Elements pageTag = parse.getElementsByClass("pagebar").get(0).getElementsByTag("a");
					lastPage = Integer.parseInt(pageTag.last().text());
					if (lastPage == 0) {
						lastPage = Integer.parseInt(pageTag.get(pageTag.size() - 2).text());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				Element seriesDivList = parse.getElementsByClass("series-list").get(0);

				Iterator<Element> seriesCf = seriesDivList.children().iterator();

				if (lastPage != 0 && page >= lastPage) {
					Message toSend = seriesHandler.obtainMessage(Const.MSG_URL_NOT_FOUND);
					seriesHandler.sendMessage(toSend);
				}

				while (seriesCf.hasNext()) {
					analize(seriesList, seriesCf);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return seriesList;
		}

		private void analize(List<Series> seriesList, Iterator<Element> seriesCf) {
			Element next = seriesCf.next();
			Element seriesDescribe = next.getElementsByClass("series-describe").get(0);
			Element title = seriesDescribe.getElementsByIndexEquals(0).get(0).child(0).child(0);

			String seriesUrl = title.absUrl("href");
			String titleStr = title.ownText();

			String coverUrl = seriesDescribe.getElementsByTag("img").get(0).absUrl("src");

			String describe = seriesDescribe.getElementsByIndexEquals(2).get(0).text();

			Element moreDescribe = next.getElementsByClass("more-describe").get(0);

			int total = 0;
			try {
				total = Integer.parseInt(moreDescribe.text().replace("共", "").replace("话", ""));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}

			Element firstUrlA = moreDescribe.getElementsByClass("button").get(0);
			String firstUrl = firstUrlA.absUrl("href");
			// String firstUrl = moreDescribe.getElementsByTag("a").get(0)
			// .absUrl("href");

			seriesList.add(new Series(null, seriesUrl, titleStr, coverUrl, describe, total, firstUrl));
		}
	}
}